package BinarySortTree;

/*
平衡二叉树
给定一个二叉树，判断它是否是 平衡二叉树

示例 1：
输入：root = [3,9,20,null,null,15,7]
输出：true
示例 2：
输入：root = [1,2,2,3,3,null,null,4,4]
输出：false
示例 3：
输入：root = []
输出：true

作者：LeetCode
链接：https://leetcode.cn/leetbook/read/introduction-to-data-structure-binary-search-tree/xmx4r7/
 */

public class _41平衡二叉树 {
    public static void main(String[] args) {

    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        boolean flag = true;
        public boolean isBalanced(TreeNode root) {
            maxDepth(root);
            return flag;
        }

        public int maxDepth(TreeNode root) {
            if(!flag)
                return 0;
            if (root == null) {
                return 0;
            }
            int leftDepth = maxDepth(root.left);
            int rightDepth = maxDepth(root.right);
            if (Math.abs(leftDepth - rightDepth) > 1) {
                flag = false;
            }
            return Math.max(leftDepth, rightDepth) + 1;
        }
    }

}
